<?php
class Sfs_ModuleConfig extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch()
    {

        // 取得 vie
        $view = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->view;
        // 取得 認證
        $auth = Zend_Auth::getInstance();

        if (isset($view->School))
        return;

        //  取得是否通過認證
        $view->authenticated = $auth->hasIdentity();

        // 取得使用者資訊
        $user = new Sfs_Model_User($auth->getIdentity());

        $view->user = $user->getUser();

        // 取得網頁基本路徑
        $view->baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();

        $view->baseScript = $view->baseUrl.'/'. $this->_request->getModuleName().'/'.$this->_request->getControllerName();

        // 含網址路徑
        if (isset($_SERVER['HTTPS']))
        $view->baseHttpUrl = 'https://'.$_SERVER["HTTP_HOST"].$view->baseScript;
        else
        $view->baseHttpUrl = 'http://'.$_SERVER["HTTP_HOST"].$view->baseScript;

        // Controller 名稱
        $view->ControllerName = $this->_request->getControllerName();

        //目前程式 url
        $view->scriptUrl = $this->_request->getModuleName().'/'. $this->_request->getControllerName();

        //目前程式 Action
        $view->scriptAction = $this->_request->getActionName();


        // 學校資料
        $cache = Zend_Registry::get('cache');

        if(!$result = $cache->load('school')) {
            $view->School = Doctrine_Core::getTable('School_Model_School')->findAll()->getFirst()->toArray();
            $cache->save($view->School,'school');
        }
        else
        $view->School=  $result;

        $len= $view->School['length'];
        $arr = explode("-",$len);
        $view->lowYear = $arr[0];
        $view->highYear = $arr[1];

        $view->headTitle()->setSeparator(' - ');
        $view->headTitle()->prepend($view->School['name_short']);
        $view->year_name = unserialize($view->School['length_name']);
        // 學期資料
        if(!$result = $cache->load('semester')) {
            $semester_duration = new Semester_Model_SemesterDuration();
            $view->Semester =  $semester_duration->get_curr_year_seme();
            $cache->save($view->Semester,'semester');
        }
        else
        $view->Semester = $result;

        // 模組資料
        $resource = new Default_Model_Resources();

        $module = $resource->getTable()->findOneBy('id',$this->_request->getModuleName());

        if ($module) {
            $controller = $this->_request->getControllerName();
            $view->Controller = $controller;

            $view->ModuleInfo = $module->toArray();
            $view->headTitle()->prepend($view->ModuleInfo['title']) ;
            $translate = Zend_Registry::get('Zend_Translate');
            $tr_name = APPLICATION_PATH.'/modules/'.$this->_request->getModuleName().'/languages/'.$translate->getLocale().'/'.
            $this->_request->getModuleName().'.php';
            if (is_file($tr_name)){
                $translate->addTranslation($tr_name);
            }
            $tr_name = APPLICATION_PATH.'/modules/'.$this->_request->getModuleName().'/languages/'.$translate->getLocale().'/'.
            $this->_request->getControllerName().'.php';
            if (is_file($tr_name)){
                $translate->addTranslation($tr_name);
            }
            if (Zend_Registry::isRegistered('moduleConfig')) {
                if ($menu = Zend_Registry::get('moduleConfig')->menu and $controller != 'login'){
                    $this->_initMenu($menu);
                }
            }
        }

    }



    public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {
        // 儲存模組設定
        $moduleName  = APPLICATION_PATH.'/modules/'.$request->getModuleName(). '/module.xml';
        if (is_file($moduleName)){
            $result  = new Zend_Config_Xml($moduleName);
            Zend_Registry::set('moduleConfig',$result);
        }


        $frontController = Zend_Controller_Front::getInstance();
        $bootstrap =  $frontController->getParam('bootstrap');
        $activeModuleName = $request->getModuleName();
        $moduleList = $bootstrap->modules;

        $moduleInitName = strtolower($activeModuleName)."Init";
        $moduleInitNameLength = strlen($moduleInitName);

        if (isset($moduleList[$activeModuleName])) {
            $activeModule = $moduleList[$activeModuleName];

            $bootstrapMethodNames = get_class_methods($bootstrap);
            foreach ($bootstrapMethodNames as $key=>$method) {
                $runMethod = false;
                $methodNameLength = strlen($method);
                if ($moduleInitNameLength < $methodNameLength && $moduleInitName == substr($method,0,$moduleInitNameLength)) {
                    call_user_func(array($bootstrap,$method));
                }
            }
        }
        else {
            $activeModule = $bootstrap;
        }

        $methodNames = get_class_methods($activeModule);
        foreach ($methodNames as $key=>$method) {
            $runMethod = false;
            $methodNameLength = strlen($method);
            if (10 < $methodNameLength && 'activeInit' === substr($method, 0, 10)) {
                $runMethod = true;
            }
            elseif ($moduleInitNameLength < $methodNameLength && $moduleInitName == substr($method,0,$moduleInitNameLength)) {
                $runMethod = true;
            }
            if ($runMethod) {
                call_user_func(array($activeModule,$method));
            }
        }
    }

    /**
     *  選單
     * @param unknown_type $menu
     */
    private function _initMenu($menu)
    {

        //TODO 檢查如 json 則 傳回 false;
        $fc = Zend_Controller_Front::getInstance();
        $moduleName = $fc->getRequest()->getModuleName();

        $moduleXml  = APPLICATION_PATH.'/modules/'.$moduleName. '/module.xml';

        $username = Zend_Auth::getInstance()->getIdentity()->username;
        if (!$username)
        $username = 'Guest';
        $acl = Zend_Registry::get('acl');

        if ($menu->item->url)
        $tempMenu[(string)$menu->item->url] = $menu->item->toArray();
        else
        foreach ($menu->item as $val)
        $tempMenu[(string)$val->url] = $val->toArray();

        $arr = array();
        $resourceName = $moduleName.':'.$fc->getRequest()->getControllerName();

        if ($acl->has($resourceName) and !$acl->isAllowed($username,$resourceName))
        return false;

        if ($acl->isAllowed($username,$moduleName))
        $arr = $tempMenu;

        foreach ($tempMenu as $val) {
            $resourceName = $moduleName.':'.$val['url'];
            if ($acl->has($resourceName) ) {
                if ($acl->isAllowed($username,$resourceName))
                $arr[$val['url']] = $val;
                else {
                    if (in_array($val['url'],array_keys($arr)))
                    unset($arr[$val['url']]);
                }
            }

        }
        $view = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->view;
        // 將 controller name 加到 title
        $controllerName = $fc->getRequest()->getControllerName() ;
        if ($controllerName != '')  {
            if (isset($arr[$controllerName]['name'])) {
                $ss = $arr[$controllerName]['name'];
                $translate = Zend_Registry::get('Zend_Translate');
                $view->HeadTitle =  $translate->_($ss);
                $view->headTitle()->prepend($view->HeadTitle);
            }
        }
        // 設定選單陣列
        $view->navMenu =  $arr;

        // 設定第一個執行的 controller
        if (count($arr))
        $view->itemIndex = $moduleName.'/'.key($arr);
        else
        $view->itemIndex = '/';

    }

}
